<?php
session_start();
header("Content-type: text/html; charset=utf-8");
require_once 'include/baidu/AipSpeech.php';
class main extends spController
{   
    private $allowed_referers = [];
    private $apiKey;
    private $secretKey;
    private $accessToken;
    private $tokenExpires = 0;
    private $YGKey;
    private $YGSecretKey;
    function __construct(){
        parent::__construct();        
        $this->ac = $GLOBALS['_GET']['a'];
        $this->con = $GLOBALS['_GET']['c']; 
        //获取当前IP 写入到cookies
        $ip = $this->ip();
        setcookie("client_ip",$ip);
      	$this->top_keywords = "博雅秘库,古籍,古诗,成语,作者,古文,诗词,文言文,中国,古典,经典,唐诗三百首";
        $this->user_id = "";
        if(isset($_SESSION['user_id'])){
            $this->user_id = $_SESSION['user_id'];
        }
        $this->allowed_referers = ['http://127.0.0.1:8055/', 'http://localhost:8055/']; // 添加允许的来源
        $baidu_config = spExt('baidu');
        $this->apiKey = $baidu_config['apiKey'];
        $this->secretKey = $baidu_config['secretKey'];
        $this->YGKey = $baidu_config['YGKey'];
        $this->YGSecretKey = $baidu_config['YGSecretKey'];
    }
    function ip() {
        //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
        return $res;
        //dump(phpinfo());//所有PHP配置信息
    }
    /**
     * 生成音频
     * @param string $text 要生成的文本
     * @return string 音频文件路径
     */
    function createAudio($text){
        $APP_ID = '60876582';
        $API_KEY = $this->apiKey;
        $SECRET_KEY = $this->secretKey;
        // 过滤掉$text 文本中的html标签
        $text = strip_tags($text);
        // 过滤掉$text 文本中的特殊字符
        $text = htmlspecialchars($text);
        $client = new AipSpeech($APP_ID, $API_KEY, $SECRET_KEY);
        $res = $client->synthesis($text, 'zh', 1, array(
            'vol' => 5,
            'per' => 4,
            'spd' => 5,
            'pit' => 5,
        ));
        
        if(!is_array($res)){
            $file = fopen('audio/'.time().'.mp3', 'wb');
            fwrite($file, $res['data']);
            fclose($file);
            return 'audio/'.time().'.mp3';
        }
        return false;
    }
    /**
     * 提交转换文本返回生成的音频文件路径
     * @param string $text 要转换的文本
     * @return string 音频文件路径
     */
    function createAudioSubmit(){
        $text = $this->spArgs('text');
        if(empty($text)){
            $this->ajaxReturn(array('code'=>0,'msg'=>'请输入要转换的文本'));
        }
        $audio = $this->createAudio($text);
        if($audio != false){
            $this->ajaxReturn(array('code'=>1,'msg'=>'转换成功','data'=>$audio));
        }
        $this->ajaxReturn(array('code'=>0,'msg'=>'转换失败','data'=>$audio));
    }


    function index(){
      	$zd_gushi = spClass("zd_gushi");
        $zd_book = spClass("zd_book");
        $zd_chengyu = spClass("zd_chengyu");
        $zd_authors = spClass("zd_authors");
        //随机获取40个作者
        $re_author = $zd_authors->findSql("SELECT * FROM zd_authors where pic<>'' and status=1 ORDER BY RAND() LIMIT 40");
        $this->authors = $re_author;
        //获取今日推荐古诗2条
      	$gushiRemand = $zd_gushi->findSql("SELECT * FROM zd_gushi ORDER BY RAND() LIMIT 6");
        
        // 遍历新增字段名为场景图，使用https://picsum.photos/id/110/600/400 类似的图片随机出现
        foreach($gushiRemand as $key=>$val){
            $gushiRemand[$key]['scene'] = "https://picsum.photos/600/400";
        }
        $this->gushir = $gushiRemand;
        //获取今日推荐古籍4条
        $re_book = $zd_book->findSql("SELECT * FROM zd_book where pic<>'' ORDER BY RAND() LIMIT 4");
        $this->books = $re_book;
        $re_books = $zd_book->findSql("SELECT id,title FROM zd_book where pic<>'' and bstatus=1 ORDER BY RAND() LIMIT 20");
        $this->bs = $re_books;
        //获取今日推荐成语6条
      	$re_chengyu = $zd_chengyu->findSql("SELECT * FROM zd_chengyu ORDER BY RAND() LIMIT 6");
        $this->chengyus = $re_chengyu;
        $re_chengyus = $zd_chengyu->findSql("SELECT id,title FROM zd_chengyu ORDER BY RAND() LIMIT 40");
        $this->cys = $re_chengyus;
        $this->html_title = "简说古诗-古诗词、古籍经典传承";
        $this->html_desc = "简说古诗作为传承经典的网站成立于2018年。古诗词网专注于古诗文服务，致力于让古诗文爱好者更便捷地发表及获取古诗文相关资料。";
        // 获取推荐文章5条
        
        
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/index.html');
        }else{
            $this->display('v2/index.html');
        }
	}
	function gushi(){
        //获取古诗列表
        $zd_gushi = spClass("zd_gushi");
        $f = $this->spArgs("f");
        $v = $this->spArgs("v");
        $this->fv = $f;
        $this->vv = $v;
        $condition = array("1"=>1);
        if(!empty($f)){
            $condition[$f]=$v;
        }
        $this->result = $zd_gushi->spPager($this->spArgs('page', 1), 10)->findAll($condition,"id DESC");
        $this->pager = $zd_gushi->spPager()->getPager();
		$this->html_title = "简说古诗-古诗词、古籍经典传承";
        $this->html_desc ="简说古诗作为传承经典的网站成立于2018年。古诗词网专注于古诗文服务，致力于让古诗文爱好者更便捷地发表及获取古诗文相关资料。";
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/gushiList.html');
        }else{
            $this->display('v2/gushiList.html');
        }
    }
    /**
     * 获取古诗列表
     * 接口入参：dynasty=all&theme=all&form=all&page=2&limit=6
     * 接口出参：{
                    "success": true,
                    "data": [
                        {
                        "id": 1,
                        "title": "静夜思",
                        "author": "李白",
                        "dynasty": "唐",
                        "form": "五言绝句",
                        "content": "床前明月光，疑是地上霜。举头望明月，低头思故乡。",
                        "image": "https://picsum.photos/id/29/600/400",
                        "views": "2.3k",
                        "likes": 568
                        },
                        // 更多诗词...
                    ]
                }
     */
    function getGuShiList(){
        $dynasty = $this->spArgs("dynasty");
        $dynasty = $dynasty == "all" ? "" : $dynasty;
        $theme = $this->spArgs("theme");
        $theme = $theme == "all" ? "" : $theme;
        $form = $this->spArgs("form");
        $form = $form == "all" ? "" : $form;
        $page = $this->spArgs("page",1);
        $limit = $this->spArgs("limit",9);
        $keyword = $this->spArgs("keyword","");
        $zd_gushi = spClass("zd_gushi");
        $condition = " 1=1 ";
        if(!empty($dynasty)){
            $condition .= " and dynasty='$dynasty'";
        }
        if(!empty($theme)){
            $condition .= " and tags like '%$theme%'";
        }
        if(!empty($form)){
            $condition .= " and form='$form'";
        }
        if(!empty($keyword)){
            $condition .= " and (title like '%$keyword%' or content like '%$keyword%' or author like '%$keyword%' or dynasty like '%$keyword%' or tags like '%$keyword%' or form like '%$keyword%')";
        }
        $result = $zd_gushi->spPager($page, $limit)->findAll($condition,"id DESC");
        // 重构返回列表，添加字段
        $redisObj = spClass('ZDRedis');
        $newlist = [];
        foreach($result as $key=>$val){
            // 添加浏览量字段
            $id = $val["id"];
            $redis_key = "gushi_".$id;
            $nums = $redisObj->get($redis_key);      
            if(empty($nums) || $nums/1 == 0){
                $nums = 0;
            }
            // 将$nums的值转换为*k、*w等类型展示，如果小于1000则直接展示
            if($nums/1000 > 1){
                $nums = intval($nums/1000)."k";
            }else if($nums/1000000 > 1){
                $nums = intval($nums/1000000)."w";
            }else{
                $nums = intval($nums)."次";
            }
            $newlist[$key]["views"] = $nums;
            // 获取喜欢数
            $key_like = "gushi_num_".$id;
            $like = $redisObj->get($key_like);
            if(empty($like) || $like/1 == 0){
                $like = 0;
            }
            $newlist[$key]["likes"] = $like;
            // 添加内容字段 去掉内容中的换行符
            $newlist[$key]["content"] = str_replace("\\n","",$val["content"]);
            // 添加作者字段
            $newlist[$key]["author"] = $val["author"];
            // 添加朝代字段
            $newlist[$key]["dynasty"] = $val["dynasty"];
            // 添加类型字段
            $newlist[$key]["form"] = $val["form"];
            // 添加标题字段
            $newlist[$key]["title"] = $val["title"];  
            // 添加标签字段
            $newlist[$key]["tags"] = $val["tags"];
            // 添加id字段
            $newlist[$key]["id"] = $val["id"];
        }
        // $pager = $zd_gushi->spPager()->getPager();
        $this->AjaxReturn(1,"success",$newlist);
    }
    function chengyu(){
    	//获取成语列表
        $zd_chengyu = spClass("zd_chengyu");
        $f = $this->spArgs("f");
        $v = $this->spArgs("v");
        $this->fv = $f;
        $this->vv = $v;
        $condition = array("1"=>1);
        if(!empty($f)){
            $condition[$f]=$v;
        }
        $this->result = $zd_chengyu->spPager($this->spArgs('page', 1), 10)->findAll($condition,"id DESC");
        $this->pager = $zd_chengyu->spPager()->getPager();
		$this->html_title = "简说古诗-古诗词、古籍经典传承";
        $this->html_desc ="简说古诗作为传承经典的网站成立于2018年。古诗词网专注于古诗文服务，致力于让古诗文爱好者更便捷地发表及获取古诗文相关资料。";
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/chengyuList.html');
        }else{
            $this->display('v2/chengyuList.html');
        }	
    }
    /**
     * 获取古籍内容
     * @param int $id 古籍id
     * @param int $page 页码
     */
    function getBookContent(){
        $page = $this->spArgs("page",1);
        $id = $this->spArgs("id",0);
        // 通过书籍ID获取章节列表，然后通过章节ID获取章节内容
        $zd_booklist = spClass("zd_booklist");
        // 章节通过sort排序 $page 就是页码，每次获取一条内容
        $condition = array("bid"=>$id);
        $result = $zd_booklist->spPager($page, 1)->findAll($condition,"sort ASC");
        $pager = $zd_booklist->spPager()->getPager();
        if(empty($result) || $result == false || count($result)<=0){
            $this->AjaxReturn(0,"没有更多内容了");
        }
        $zjid = $result[0]["id"];
        // 通过章节ID获取章节内容
        $zd_bookcontent = spClass("zd_bookcontent");
        $condition = array("blid"=>$zjid);
        $result = $zd_bookcontent->find($condition);
        if(empty($result) || $result == false || count($result)<=0){
            $this->AjaxReturn(0,"没有更多内容了");
        }
        $this->AjaxReturn(1,"success",['book'=>$result,'pager'=>$pager]);
    }
    /**
     * 获取古籍列表
     */
    function getBooks(){
        $page = $this->spArgs("page",1);
        $pagesize = $this->spArgs("pageSize",6);
        $category = $this->spArgs("category","");
        $keyword = $this->spArgs("keyword","");
        $type = $this->spArgs("type",""); // popular 获取热门 featured 获取精选

        $zd_book = spClass("zd_book");
        $condition = " bstatus=1 ";
        if(!empty($category)){
            $condition .= " and tags like '%$category%'";
        }
        if(!empty($keyword)){
            $condition .= " and title like '%$keyword%'";
        }
        if(!empty($keyword)){
            $condition .= " and (intro like '%$keyword%' or author like '%$keyword%' or tags like '%$keyword%' or title like '%$keyword%')";
        }
        if(!empty($type)){
            if($type == "popular"){
                $condition .= " and views > 0";
            }else if($type == "featured"){
                $condition .= " and featured = 1";
            }
        }

        $result = $zd_book->spPager($page, $pagesize)->findAll($condition,"id DESC");
        $newlist = [];
        foreach($result as $key=>$val){
            $newlist[$key]["id"] = $val["id"];
            $newlist[$key]["title"] = $val["title"];
            $newlist[$key]["author"] = $val["author"];
            $newlist[$key]["niandai"] = $val["niandai"];
            // 控制长度
            if(strlen($val["intro"]) > 100){
                $newlist[$key]["description"] = substr($val["intro"],0,100)."...";
            }else{
                $newlist[$key]["description"] = $val["intro"];
            }
            $newlist[$key]["pic"] = "https://picsum.photos/400/600";
            $newlist[$key]["tags"] = $val["tags"];
            
        }
        // 添加清理UTF-8字符的函数
        function cleanUtf8($data) {
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $data[$key] = cleanUtf8($value);
                }
            } elseif (is_object($data)) {
                foreach ($data as $key => $value) {
                    $data->$key = cleanUtf8($value);
                }
            } elseif (is_string($data)) {
                // 移除无效的UTF-8字符
                $data = iconv('UTF-8', 'UTF-8//IGNORE', $data);
            }
            return $data;
        }
        
        try{
            // 调试信息
            // print_r($newlist);
            
            // 检查数据类型
            if(!is_array($newlist) && !is_object($newlist)){
                throw new Exception('数据不是数组或对象');
            }
            
            // 清理无效的UTF-8字符
            $cleanedNewlist = cleanUtf8($newlist);
            
            // 尝试JSON编码
            $jsonResult = json_encode(
                [
                    "code"=>1,
                    "msg"=>"success",
                    "data"=>$cleanedNewlist
                ],
                JSON_UNESCAPED_UNICODE
            );
            
            // 检查编码是否成功
            if($jsonResult === false){
                throw new Exception('JSON编码失败: ' . json_last_error_msg());
            }
            
            // 确保没有之前的输出
            if(ob_get_length()){
                ob_clean();
            }
            
            // 设置正确的Content-Type
            header('Content-Type: application/json; charset=utf-8');
            echo $jsonResult;
            exit();
        }catch(\Exception $e){
            // 确保没有之前的输出
            if(ob_get_length()){
                ob_clean();
            }
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode([
                "code"=>0,
                "msg"=>"获取失败: " . $e->getMessage(),
                "data"=>null
            ], JSON_UNESCAPED_UNICODE);
            exit();
        }
    }
    /**
     * 获取古籍章节列表
     * @param int $id 古籍ID
     */
    function getBookChapter(){
        $id = $this->spArgs("id");
        $zd_booklist = spClass("zd_booklist");
        $result = $zd_booklist->findAll(['bid'=>$id],"sort ASC",'id,title');
        if($result == false){
            $this->AjaxReturn(0,"获取失败");
        }
        $this->AjaxReturn(1,"获取成功",[
            "list"=>$result
        ]);
    }
    /**
     * 获取古籍详情
     */
    function getBookDetail(){
        $id = $this->spArgs("id");
        $zd_book = spClass("zd_book");
        $result = $zd_book->find(['id'=>$id]);
        if($result == false){
            $this->AjaxReturn(0,"获取失败");
        }
        
        $result["coverUrl"] = "https://picsum.photos/600/800?random=".rand(1,100);
        

        $this->AjaxReturn(1,"获取成功",[
            "book"=>$result
        ]);
    }
    /**
     * 切换收藏状态（收藏/取消收藏）
     */
    function toggleCollection() {
        // 验证用户是否登录
        if (!isset($_SESSION['user_id'])) {
            $this->ajaxReturn(0, '请先登录');
        }
        
        $book_id = $this->spArgs('book_id');
        if (empty($book_id)) {
            $this->ajaxReturn(0, '参数错误');
        }
        
        $user_id = $_SESSION['user_id'];
        $zd_collect = spClass('zd_user_collections');
        
        // 检查是否已收藏
        $condition = array(
            'user_id' => $user_id,
            'book_id' => $book_id
        );
        $collect = $zd_collect->find($condition);
        
        if ($collect) {
            // 已收藏，执行取消收藏
            $result = $zd_collect->delete($condition);
            if ($result) {
                $this->ajaxReturn(1, '取消收藏成功', array('is_collected' => false));
            } else {
                $this->ajaxReturn(0, '取消收藏失败');
            }
        } else {
            // 未收藏，执行收藏
            $data = array(
                'user_id' => $user_id,
                'book_id' => $book_id,
                'created_at' => date('Y-m-d H:i:s')
            );
            $result = $zd_collect->create($data);
            if ($result) {
                $this->ajaxReturn(1, '收藏成功', array('is_collected' => true));
            } else {
                $this->ajaxReturn(0, '收藏失败');
            }
        }
    }

    /**
     * 检查书籍是否已收藏
     */
    function checkCollection() {
        if (!isset($_SESSION['user_id'])) {
            $this->ajaxReturn(0, '未登录', array('is_collected' => false));
        }
        
        $book_id = $this->spArgs('book_id');
        if (empty($book_id)) {
            $this->ajaxReturn(0, '参数错误');
        }
        
        $zd_collect = spClass('zd_user_collections');
        $collect = $zd_collect->find(array(
            'user_id' => $_SESSION['user_id'],
            'book_id' => $book_id
        ));
        
        $this->ajaxReturn(1, '', array('is_collected' => !empty($collect)));
    }
    function guji(){
    	//获取古籍列表
        $zd_book = spClass("zd_book");
        $f = $this->spArgs("f");
        $v = $this->spArgs("v");
        $this->fv = $f;
        $this->vv = $v;
        $condition = array("bstatus"=>1);
        if(!empty($f)){
            $condition[$f]=$v;
        }
        $this->result = $zd_book->spPager($this->spArgs('page', 1), 10)->findAll($condition,"id DESC");
        $this->pager = $zd_book->spPager()->getPager();
		$this->html_title = "简说古诗-古诗词、古籍经典传承";
        $this->html_desc ="简说古诗作为传承经典的网站成立于2018年。古诗词网专注于古诗文服务，致力于让古诗文爱好者更便捷地发表及获取古诗文相关资料。";
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/bookList.html');
        }else{
            $this->display('v2/bookList.html');
        }
    }
    /**
     * 互动体验
     */
    function interactive(){
        $this->display('v2/interactive.html');
    }
    /**
     * 经典诗词
     */
    function classics(){
        $this->display('v2/classics.html');
    }
    /**
     * 创作
     */
    function zuoze(){
    	//获取作者列表
        // $zd_authors = spClass("zd_authors");
        // $f = $this->spArgs("f");
        // $v = $this->spArgs("v");
        // $this->fv = $f;
        // $this->vv = $v;
        // $condition = array("status"=>"1");
        // if(!empty($f)){
        //     $condition[$f]=$v;
        // }
        // $this->result = $zd_authors->spPager($this->spArgs('page', 1), 10)->findAll($condition,"sort DESC");
        // $this->pager = $zd_authors->spPager()->getPager();
		// $this->html_title = "简说古诗-古诗词、古籍经典传承";
        // $this->html_desc ="简说古诗作为传承经典的网站成立于2018年。古诗词网专注于古诗文服务，致力于让古诗文爱好者更便捷地发表及获取古诗文相关资料。";
        
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/authorList.html');
        }else{
            $this->display('v2/authorList.html');
        }
    }
    /**
     * 格式化古诗内容，为指定词语添加注释弹窗
     * 
     * @param string $poem_content 古诗内容，每行一句，使用换行分隔
     * @param array $annotations 注释数组，格式：['词语' => '注释内容']
     * @return string 格式化后的HTML字符串
     */
    function format_poem($poem_content, $annotations = []) {
        // 分割诗句为行数组
        $lines = explode("\n", $poem_content);
        $formatted_lines = [];
        
        // 处理注释词语：按长度排序，避免短词语先替换导致长词语无法匹配
        uksort($annotations, function($a, $b) {
            return strlen($b) - strlen($a);
        });
        
        // 生成替换规则的正则表达式和替换值
        $search = [];
        $replace = [];
        foreach ($annotations as $word => $note) {
            // 转义特殊字符，确保正则匹配正确
            $escaped_word = preg_quote(trim($word), '/');
            $search[] = '/(' . $escaped_word . ')/u';
            $replace[] = '<span class="annotation-hover">$1<span class="annotation-popup">' . htmlspecialchars($note, ENT_QUOTES, 'UTF-8') . '</span></span>';
        }
        
        // 处理每行诗句
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) continue;
            
            // 应用替换规则
            $formatted_line = preg_replace($search, $replace, $line);
            
            // 包裹p标签
            $formatted_lines[] = '<p class="mb-4">' . $formatted_line . '</p>';
        }
        
        // 拼接所有行并返回
        return implode("\n", $formatted_lines);
    }
    function gsDetails(){
        $zd_gushi = spClass("zd_gushi");
        $id = $this->spArgs("id");
        $gushi = $zd_gushi->find(array("id"=>$id));
        $zd_authors = spClass("zd_authors");
        $authors = $zd_authors->find(array("title"=>$gushi["author"]));
        $this->authors = $authors;
        // 将古诗标签转换为数组
        $gushi["tags"] = explode("，",$gushi["tags"]);
        // 添加浏览量字段
        $redisObj = spClass('ZDRedis');
        $key = "gushi_".$id;
        $nums = $redisObj->get($key);      
        if(empty($nums) || $nums/1 == 0){
            $ns = rand(875, 1900);
        	$redisObj->set($key,$ns);
            $gushi['num'] = $ns;
        }else{
        	$gushi['num'] = $nums/1+1;
            $redisObj->set($key,$gushi['num']);
        }
        // 将$gushi['num']的值转换为*k、*w等类型展示，如果小于1000则直接展示
        if($gushi['num']/1000 > 1){
            $gushi['num'] = intval($gushi['num']/1000)."k";
        }else if($gushi['num']/1000000 > 1){
            $gushi['num'] = intval($gushi['num']/1000000)."w";
        }else{
            $gushi['num'] = intval($gushi['num'])."次";
        }
        // 获取喜欢数
        $key_like = "gushi_num_".$id;
        $like = $redisObj->get($key_like);
        if(empty($like) || $like/1 == 0){
            $gushi['like'] = 0;
        }else{
            $gushi['like'] = $like/1;
        }
        /**
         * 古诗内容格式化，可以参考如下示例对古诗内容进行格式化
         * <p class="mb-4">床前明月光，<span class="annotation-hover">疑是<span class="annotation-popup">怀疑是，好像是</span></span>地上霜。</p>
         * <p class="mb-4"><span class="annotation-hover">举头<span class="annotation-popup">抬头</span></span>望明月，<span class="annotation-hover">低头<span class="annotation-popup">低下头</span></span>思故乡。</p>
         * 此处关于古诗的词语注释需要通过大模型进行提取，提取的词语注释需要包含在注释数组中，格式为：['词语' => '注释内容'] ------------------------------
         */
        $gushi['content'] = $this->format_poem($gushi['content'],array( ));
        // 将内容中的\n替换为<br>
        $gushi['content'] = str_replace("\\n","<br>",$gushi['content']);
        // 将内容中的\r替换为<br>
        $gushi['content'] = str_replace("\n","<br>",$gushi['content']);
        // 遇到句号、问号、感叹号等标点符号后添加<br>
        $gushi['content'] = preg_replace('/([。？！])/u', '$1<br>', $gushi['content']);
        $this->result = $gushi;
        
        //获取相关古诗
        $res_gushi = $zd_gushi->findSql("select * from zd_gushi where dynasty like '%".$gushi["dynasty"]."%' and author like '%".$gushi["author"]."%' order by RAND() desc limit 6");
        $this->res_gushi = $res_gushi; 
        
        // 输出地址
        $this->url_painting = "javascript:showToast('请先登录', true);";
        $this->url_continue = "javascript:showToast('请先登录', true);";
        if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
            $this->url_painting = spUrl('creation','painting',array('id'=>$id,'title'=>$gushi['title']));
            $this->url_continue = spUrl('creation','continuePoem',array('id'=>$id,'title'=>$gushi['title']));
        }
        
        $this->html_title = $authors['title']."-".$gushi['title']."-博雅秘库-简说古诗-古诗词、古籍经典传承";
        $this->html_desc =substr($this->cutstr_html($authors['intro']),0,200);
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        $this_keywords = $gushi["dynasty"].",".$gushi["author"];
      	foreach($res_gushi as $g){
        	$this_keywords .= ",".$g["title"].",".$g["author"]; 
        }
      	$this->top_keywords = "博雅秘库,古籍,古诗,成语,作者,古文,诗词,文言文,中国,古典,经典,唐诗三百首.".$this_keywords;
      	
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/gushi.html');
        }else{
            $this->display('v2/gushi.html');
        }    
    }
    function gsData(){
        $zd_gushi = spClass("zd_gushi");
        $id = $this->spArgs("id");
        $gushi = $zd_gushi->find(array("id"=>$id));
        echo json_encode(array('code'=>0,'data'=>$gushi));
    }
    function gjDetails(){
        $zd_book = spClass("zd_book");
        $id = $this->spArgs("id");
        $book = $zd_book->find(array("id"=>$id));

        // 获取与这个古籍相关的其他古籍3本
        $res_guji = $zd_book->findSql("select * from zd_book order by RAND() desc limit 3");
        // 重新设置古籍封面
        foreach($res_guji as $key=>$val){
            $res_guji[$key]["coverUrl"] = "https://picsum.photos/120/160?random=".rand(1,100);
        }
        $this->res_guji = $res_guji;
        $this->html_title = $book['title']."博雅秘库-简说古诗-古诗词、古籍经典传承";
        $this->html_desc =substr($this->cutstr_html($book['intro']),0,200);
      
        $this_keywords = $book["title"].",".$book["author"].",".$book["niandai"];
      	
      	$this->top_keywords = "博雅秘库,古籍,古诗,成语,作者,古文,诗词,文言文,中国,古典,经典,唐诗三百首.".$this_keywords;
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/book.html');
        }else{
            $this->display('v2/book.html');
        }    
    }
    function zzDetails(){
        $zd_author = spClass("zd_authors");
        $id = $this->spArgs("id");
        $title = $this->spArgs("tl");
        if(!empty($title)){
        	$author = $zd_author->find(array("title"=>$title));
        }else{
        	$author = $zd_author->find(array("id"=>$id));
        }
        $this->author = $author;
        $zd_gushi = spClass("zd_gushi");
        $res = $zd_gushi->findAll(array("author"=>$author['title']),"id desc","*","8");
      	$this->gushi = $res;
        $this->html_title = $author['title']."简说古诗-古诗词、古籍经典传承";
        $this->html_desc =substr($this->cutstr_html($author['intro']),0,200);
      
        $this_keywords = $author["title"].",".$author["intro"];
      	foreach($res as $g){
        	$this_keywords .= ",".$g["title"]; 
        }
      	$this->top_keywords = "博雅秘库,古籍,古诗,成语,作者,古文,诗词,文言文,中国,古典,经典,唐诗三百首.".$this_keywords;
        
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/author.html');
        }else{
            $this->display('v2/author.html');
        }    
    }
    function zj(){
        $zd_book = spClass("zd_book");
        $zd_bookcontent = spClass("zd_bookcontent");
        $zd_booklist = spClass("zd_booklist");
      
      
        $id = $this->spArgs("id");		//章节ID
        $bid = $this->spArgs("bid");	//书籍ID
        $this->id = $id;
        $this->bid = $bid;
      
        $book = $zd_book->find(array("id"=>$bid));        
        $this->result = $book; 		//书籍数据 
        
        $zjRes = $zd_bookcontent->find(array("blid"=>$id));
        $this->zj = $zjRes;			//章节数据
        
        $bl = $zd_booklist->find(array("id"=>$id));
        $this->bl = $bl;			//章节标题
      
      	$zd_booklist = spClass("zd_booklist");
        $res_next = $zd_booklist->findSql("select id from zd_booklist where bid=$bid and id>$id limit 1");
        $res_pre = $zd_booklist->findSql("select id from zd_booklist where bid=$bid and id<$id ORDER BY sort desc limit 1");
        if($res_next != false){
        	$res_next = $res_next[0]['id'];
        }else{
        	$res_next = '';
        }
        if($res_pre != false){
        	$res_pre = $res_pre[0]['id'];
        }else{
        	$res_pre = '';
        }
      	$this->res_next = $res_next;
      	$this->res_pre = $res_pre;
        $this->html_title = $bl['title']."简说古诗-古诗词、古籍经典传承";
        $this->html_desc =substr($this->cutstr_html($zjRes['content']),0,100);
      
      	$this_keywords = $book["title"].",".$book["author"].",".$book["niandai"];
      	
      	$this->top_keywords = "博雅秘库,古籍,古诗,成语,作者,古文,诗词,文言文,中国,古典,经典,唐诗三百首.".$this_keywords;
      
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/zj.html');
        }else{
            $this->display('v2/zj.html');
        }    
    }
    function ajax_gushi(){
        $zd_gushi = spClass("zd_gushi");
        $f = $this->spArgs("f");
        $v = $this->spArgs("v");
        $condition = array("1"=>1);
        if(!empty($f)){
            $condition[$f]=$v;
        }
        $result = $zd_gushi->spPager($this->spArgs('page', 1), 10)->findAll($condition,"id DESC");
        $pager = $zd_gushi->spPager()->getPager();
        if(empty($pager)){
            $res['pager'] = array();
        }else{
            $res['pager'] = $pager;
        }
        $res['result'] = $result;
        echo json_encode($res);
    }
    function counter(){
        $redisObj = spClass('ZDRedis');
        $key = $this->spArgs("k");
        if(!empty($key)){
            $res = $redisObj->increment($key);
            echo json_encode(array('code'=>'0','num'=>$res));
        }else{
            echo json_encode(array('code'=>'1'));
        }
    }
  	function cutstr_html($string){  

        $string = strip_tags($string);  

        $string = trim($string);  

        $string = preg_replace("/\t/","",$string);  

        $string = preg_replace("/\r\n/","",$string);  

        $string = preg_replace("/\r/","",$string);  

        $string = preg_replace("/\n/","",$string);  

        return trim($string);  

    }
    function chulichengyu(){
    	$chengyu = spClass("zd_chengyu");
        $res = $chengyu->findSql("select * from zd_chengyu where pinyin is null or pinyin=''");
        for($i=0;$i<count($res,0);$i++){
        	$_item = $res[$i];
            $id = $_item['id'];
            $desc = $_item['desc'];
            $s_pinyin = strpos($desc,'拼音');
            if($s_pinyin != false){
                $start_pinyin = $s_pinyin+9;
                $pinyinStart = substr($desc,$start_pinyin);
                $end_pinyin = strpos($pinyinStart,'【'); 
                if($end_pinyin == false){        
                    $pinyin = $this->cutstr_html($pinyinStart);
                    //print_r($pinyin);
                }else{   
                    $pinyin = substr($pinyinStart,0,$end_pinyin);
                    $pinyin = $this->cutstr_html($pinyin);
                    //print_r($pinyin);
                }
            }
            //print_r('<br>');
            //获取解释
            $s_jieshi = strpos($desc,'解释');
            if($s_jieshi != false){
                $start_jieshi = $s_jieshi+9;
                $jieshiStart = substr($desc,$start_jieshi);
                $end_jieshi = strpos($jieshiStart,'【');
                if($end_jieshi == false){        
                    $jieshi = $this->cutstr_html($jieshiStart);
                    //print_r($jieshi);
                }else{    
                    $jieshi = substr($jieshiStart,0,$end_jieshi);
                    $jieshi = $this->cutstr_html($jieshi);
                    //print_r($jieshi);
                }
            }
            //print_r('<br>');
            //获取出处
            $s_chuchu = strpos($desc,'出处');
            if($s_chuchu != false){
                $start_chuchu = $s_chuchu+9;
                $chuchuStart = substr($desc,$start_chuchu);
                $end_chuchu = strpos($chuchuStart,'【');
                if($end_chuchu == false){        
                    $chuchu = $this->cutstr_html($chuchuStart);
                    //print_r($chuchu);
                }else{    
                    $chuchu = substr($chuchuStart,0,$end_chuchu);
                    $chuchu = $this->cutstr_html($chuchu);
                    //print_r($chuchu);
                }
            }
            //print_r('<br>');
            //获取同义词
            $s_tongyici = strpos($desc,'同义词');
            if($s_tongyici != false){
                $start_tongyici = $s_tongyici+12;
                $tongyiciStart = substr($desc,$start_tongyici);
                $end_tongyici = strpos($tongyiciStart,'【');
                if($end_tongyici == false){        
                    $tongyici = $this->cutstr_html($tongyiciStart);
                    //print_r($tongyici);
                }else{    
                    $tongyici = substr($tongyiciStart,0,$end_tongyici);
                    $tongyici = $this->cutstr_html($tongyici);
                    //print_r($tongyici);
                }    
            }
            //print_r('<br>');
            //获取反义词
            $s_fanyici = strpos($desc,'反义词');
            if($s_fanyici != false){
                $start_fanyici = $s_fanyici+12;
                $fanyiciStart = substr($desc,$start_fanyici);
                $end_fanyici = strpos($fanyiciStart,'【');
                if($end_fanyici == false){        
                    $fanyici = $this->cutstr_html($fanyiciStart);
                    //print_r($fanyici);
                }else{    
                    $fanyici = substr($fanyiciStart,0,$end_fanyici);
                    $fanyici = $this->cutstr_html($fanyici);
                    //print_r($fanyici);
                }    
            }
            //创建修改
            $upRow = array(
            	"pinyin"=>$pinyin,
                "chuchu"=>$chuchu,
                "jieshi"=>$jieshi,
                "tongyici"=>$tongyici,
                "fanyici"=>$fanyici
            );
            $chengyu->update(array("id"=>$id),$upRow);
        }
    }
    
    
    /**
    * 向百度搜索提交网页
    */
    function sendUrlToBaidu(){
        $zd_gushi = spClass("zd_gushi");
        $res = $zd_gushi->findAll(array('1'=>1),"id desc","id");
        $urls = array();
          for($i=0;$i<count($res,0);$i++){
            $it = $res[$i];
            array_push($urls,'http://gushi.phoenixfm.cn/index.php?c=main&amp;a=gsDetails&amp;id='.$it['id'].'');
        }
        $zd_authors = spClass("zd_authors");
        $res = $zd_authors->findAll(array('1'=>1),"id desc","id");
        $urls = array();
          for($i=0;$i<count($res,0);$i++){
            $it = $res[$i];
            array_push($urls,'http://gushi.phoenixfm.cn/index.php?c=main&amp;a=zzDetails&amp;id='.$it['id'].'');
        }
        $zd_book = spClass("zd_book");
        $res = $zd_book->findAll(array('1'=>1),"id desc","id");
        $urls = array();
          for($i=0;$i<count($res,0);$i++){
            $it = $res[$i];
            array_push($urls,'http://gushi.phoenixfm.cn/index.php?c=main&amp;a=gjDetails&amp;id='.$it['id'].'');
        }
      
      	$zd_alertnatehistory = spClass("zd_alertnatehistory");
        $count = $zd_alertnatehistory->findCount();
        $pages = ceil($count/10);
        $urls = array();
        for($i=0;$i<$pages;$i++){
            array_push($urls,'https://gushi.phoenixfm.cn/index.php?c=main&a=alter_historyList&f=&v=&page='.($i+1).'');
        }
       
        $api = 'http://data.zz.baidu.com/urls?site=gushi.phoenixfm.cn&token=pj7Z1noHFwKqQ2AJ';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        echo $result;
    }
    /*
    生成sitemap
    */
    function createSiteMapAuthors(){  
        $t=$this->spArgs("t");
        $start=$this->spArgs("s");
        $end=$this->spArgs("e");
        $zd_authors = spClass("zd_authors");
        $xml = '<?xml version="1.0" encoding="utf-8"?><sitemapindex>';
        $res = $zd_authors->findAll(array('status'=>1),"id desc","","".$start.",".$end."");
        if(count($res,0)>0){
            for($i=0;$i<count($res,0);$i++){
                $it = $res[$i];
                $xml .= '<sitemap>';
                $xml .= '<loc>http://www.phoenixfm.cn/index.php?c=main&amp;a=zzDetails&amp;id='.$it['id'].'</loc>';
                $xml .= '<lastmod>'.date("Y-m-d H:i:s").'</lastmod>';
                $xml .= '</sitemap>';
            }
            $xml .= '</sitemapindex>';
            header("Content-type:text/xml");
            echo $xml;
            $xml = new DOMDocument('1.0', 'utf-8');
            $xml_sitemapindex = $xml->createElement("sitemapindex");
            $xml->appendChild($xml_sitemapindex);
            for($i=0;$i<count($res,1);$i++){
                $it = $res[$i];
                $xml_sitemap = $xml->createElement("sitemap");
                $xml_sitemapindex->appendChild($xml_sitemap);
                $xml_loc = $xml->createElement("loc");
                $xml_loc->nodeValue = 'http://www.phoenixfm.cn/index.php?c=main&amp;a=zzDetails&amp;id='.$it['id'].'';
                  $xml_sitemap->appendChild($xml_loc);
                $xml_lastmod = $xml->createElement("lastmod");
                  $xml_lastmod->nodeValue = ''.date("Y-m-d H:i:s").'';
                $xml_sitemap->appendChild($xml_lastmod);
            }
            $xml->formatOutput=true;
            $xml->save("sitemap".$t.".xml");
        }else{
            echo '未查询到数据';
        }
    }
    /*
    生成sitemap
    */
    function createSiteMapGushi(){
        $t=$this->spArgs("t");
        $start=$this->spArgs("s");
        $end=$this->spArgs("e");
        $zd_gushi = spClass("zd_gushi");
        $xml = '<?xml version="1.0" encoding="utf-8"?><sitemapindex>';
        $res = $zd_gushi->findAll(null,"id desc","","".$start.",".$end."");
        if(count($res,0)>0){
            for($i=0;$i<count($res,0);$i++){
                $it = $res[$i];
                $xml .= '<sitemap>';
                $xml .= '<loc>http://www.phoenixfm.cn/index.php?c=main&amp;a=gsDetails&amp;id='.$it['id'].'</loc>';
                $xml .= '<lastmod>'.date("Y-m-d H:i:s").'</lastmod>';
                $xml .= '</sitemap>';
            }
            $xml .= '</sitemapindex>';
            header("Content-type:text/xml");
            echo $xml;
            $xml = new DOMDocument('1.0', 'utf-8');
            $xml_sitemapindex = $xml->createElement("sitemapindex");
            $xml->appendChild($xml_sitemapindex);
            for($i=0;$i<count($res,1);$i++){
                $it = $res[$i];
                $xml_sitemap = $xml->createElement("sitemap");
                $xml_sitemapindex->appendChild($xml_sitemap);
                $xml_loc = $xml->createElement("loc");
                $xml_loc->nodeValue = 'http://www.phoenixfm.cn/index.php?c=main&amp;a=gsDetails&amp;id='.$it['id'].'';
                  $xml_sitemap->appendChild($xml_loc);
                $xml_lastmod = $xml->createElement("lastmod");
                  $xml_lastmod->nodeValue = ''.date("Y-m-d H:i:s").'';
                $xml_sitemap->appendChild($xml_lastmod);
            }
            $xml->formatOutput=true;
            $xml->save("sitemap".$t.".xml");
        }else{
            echo '未查询到数据';
        }
    }
    /*
    生成sitemap
    */
    function createSiteMapGuji(){ 
        $t=$this->spArgs("t");
        $start=$this->spArgs("s");
        $end=$this->spArgs("e");
        $zd_book = spClass("zd_book");
        $xml = '<?xml version="1.0" encoding="utf-8"?><sitemapindex>';
        $res = $zd_book->findAll(array("bstatus"=>1),"id desc","","".$start.",".$end."");
        if(count($res,0)>0){
            for($i=0;$i<count($res,0);$i++){
                $it = $res[$i];
                $xml .= '<sitemap>';
                $xml .= '<loc>http://www.phoenixfm.cn/index.php?c=main&amp;a=gjDetails&amp;id='.$it['id'].'</loc>';
                $xml .= '<lastmod>'.date("Y-m-d H:i:s").'</lastmod>';
                $xml .= '</sitemap>';
            }
            $xml .= '</sitemapindex>';
            header("Content-type:text/xml");
            echo $xml;
            $xml = new DOMDocument('1.0', 'utf-8');
            $xml_sitemapindex = $xml->createElement("sitemapindex");
            $xml->appendChild($xml_sitemapindex);
            for($i=0;$i<count($res,1);$i++){
                $it = $res[$i];
                $xml_sitemap = $xml->createElement("sitemap");
                $xml_sitemapindex->appendChild($xml_sitemap);
                $xml_loc = $xml->createElement("loc");
                $xml_loc->nodeValue = 'http://www.phoenixfm.cn/index.php?c=main&amp;a=gjDetails&amp;id='.$it['id'].'';
                  $xml_sitemap->appendChild($xml_loc);
                $xml_lastmod = $xml->createElement("lastmod");
                  $xml_lastmod->nodeValue = ''.date("Y-m-d H:i:s").'';
                $xml_sitemap->appendChild($xml_lastmod);
            }
            $xml->formatOutput=true;
            $xml->save("sitemap".$t.".xml");
        }else{
            echo '未查询到数据';
        }
    }
    /**
     * 虚拟历史记录
     */
    function alter_historyList(){
        $zd_alertnatehistory = spClass("zd_alertnatehistory");
        $page = $this->spArgs("page",1);
        $f = $this->spArgs("f");
        $v = $this->spArgs("v");
        $this->fv = $f;
        $this->vv = $v;
        $condition = array("1"=>1);
        if(!empty($f)){
            $condition[$f]=$v;
        }
        $result = $zd_alertnatehistory->spPager($this->spArgs('page', $page), 10)->findAll($condition,"id DESC");
        $new_result = array();
        foreach($result as $key=>$value){
            if(!empty($value["imgslist"])){
                $value["imgslist"] = json_decode($value["imgslist"],true);
            }
            array_push($new_result,$value);
        }
        $this->result = $new_result;
        $this->pager = $zd_alertnatehistory->spPager()->getPager();
		$this->html_title = "简说古诗-古诗词、古籍经典传承";
        $this->html_desc ="简说古诗作为传承经典的网站成立于2018年。古诗词网专注于古诗文服务，致力于让古诗文爱好者更便捷地发表及获取古诗文相关资料。";
      
      	$this_keywords = "历史,虚拟历史,假设历史";
      	foreach($new_result as $g){
        	$this_keywords .= ",如果：【".$g["assumption"]."】 事件出现了这种假设，那么历史会如何发展呢？"; 
        }
      	$this->top_keywords = "博雅秘库,古籍,古诗,成语,作者,古文,诗词,文言文,中国,古典,经典,唐诗三百首.".$this_keywords;
      
        //如果访问设备是手机则跳转到手机站点
        $agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos($agent,"NetFront") || strpos($agent,"iPhone") || strpos($agent,"MIDP-2.0") || strpos($agent,"Opera Mini") || strpos($agent,"UCWEB") || strpos($agent,"Android") || strpos($agent,"Windows CE") || strpos($agent,"SymbianOS")){            
            $this->display('m/history.html');
        }else{
            $this->display('v2/history.html');
        }
    }
    /**
     *  ajax接口统一返回
     * @param int $code 状态码 0失败 1成功
     * @param string $msg 提示信息
     * @param array $data 数据
     */
    function ajaxReturn($code=0,$msg='',$data=array()){
        header("Content-type: application/json; charset=utf-8");
        $result = array(
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data
        );
        echo json_encode($result);
        exit;
    }
    /**
     * 生成随机字符串
     */
    function getRandomString($length = 6) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, strlen($chars) - 1)];
        }
        return $str;
    }
    /**
     * 获取客户端IP
     */
    function get_client_ip(){
        $ip = '';
        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
    /**
     * 注册
     */
    function register(){
        $username = $this->spArgs('register-name','');
        $email = $this->spArgs('register-email','');
        $password = $this->spArgs('register-password','');
        $confirm = $this->spArgs('register-confirm','');
        if($password != $confirm){
            $this->ajaxReturn(0,'两次密码不一致');
        }
        $zd_user = spClass("zd_user");
        $user = $zd_user->find(array("email"=>$email));
        if($user){
            $this->ajaxReturn(0,'邮箱已注册');
        }
        $user = $zd_user->find(array("loginName"=>$username));
        if($user){
            $this->ajaxReturn(0,'用户名已注册');
        }
        // 验证请求来源是不是当前网站        
        if(isset($_SERVER['HTTP_REFERER']) && !in_array($_SERVER['HTTP_REFERER'], $this->allowed_referers)){
            $this->ajaxReturn(0,'请求来源错误: ' . $_SERVER['HTTP_REFERER']);
        }
        // 生成用户ID
        $user_id = $this->getRandomString(10);
        // 使用picsum.photos网站生成默认头像
        $avatar = 'https://picsum.photos/200/300?random='.$user_id;
        // 生成随机昵称
        $nickName = $this->getRandomString(6);
        // 密码加密
        $password = md5($password.$user_id);
        $data = array(
            'loginName'=>$username,
            'pwd'=>$password,
            'email'=>$email,
            'userId'=>$user_id,
            'avatar_file'=>$avatar,
            'reg_time'=>date('Y-m-d H:i:s'),
            'reg_ip'=>$this->get_client_ip(),
            'status'=>1,
            'nickName'=>$nickName,
            'source'=>2,
            'reg_type'=>2,
        );
        $add = $zd_user->create($data);
        if($add>0){
            $this->ajaxReturn(1,'注册成功');
        }else{
            $this->ajaxReturn(0,'注册失败');
        }
    }
    /**
     * 登录
     * @param string $username 用户名
     * @param string $password 密码
     */
    function login(){
        $username = $this->spArgs('login-email','');
        $password = $this->spArgs('login-password','');
        $zd_user = spClass("zd_user");
        // 验证请求来源是不是当前网站        
        if(isset($_SERVER['HTTP_REFERER']) && !in_array($_SERVER['HTTP_REFERER'], $this->allowed_referers)){
            $this->ajaxReturn(0,'请求来源错误: ' . $_SERVER['HTTP_REFERER']);
        }
        // 验证用户名和密码是否为空
        if(empty($username) || empty($password)){
            $this->ajaxReturn(0,'用户名或密码不能为空');
        }
        // 验证用户名是否是邮箱
        if(filter_var($username, FILTER_VALIDATE_EMAIL)){
            $user = $zd_user->find(array("email"=>$username));
        }else{
            $user = $zd_user->find(array("loginName"=>$username));
        }
        if($user){
            // 密码加密
            $password = md5($password.$user['userId']);
            if($user['pwd'] == $password){
                // 登录成功，更新用户信息
                $data = array(
                    'last_login'=>date('Y-m-d H:i:s'),
                    'last_ip'=>$this->get_client_ip(),
                );
                $zd_user->update($user['id'],$data);
                // 登录成功写入Cookie
                setcookie('user_id',$user['userId'],time()+3600*24*7,'/'); // 路径设置为根目录
                setcookie('user_name',$user['loginName'],time()+3600*24*7,'/'); // 路径设置为根目录
                setcookie('user_avatar',$user['avatar_file'],time()+3600*24*7,'/'); // 路径设置为根目录
                // 登录成功写入Session
                $_SESSION['user_id'] = $user['userId'];
                $this->ajaxReturn(1,'登录成功');
            }
        }else{
            $this->ajaxReturn(0,'用户不存在');
        }
    }

    /**
     * 退出登录
     */
    function logout(){
        // 清除Cookie
        setcookie('user_id','',time()-3600,'/');
        setcookie('user_name','',time()-3600,'/');
        setcookie('user_avatar','',time()-3600,'/');
        // 清除Session
        session_unset();
        session_destroy();
        $this->ajaxReturn(1,'退出成功');
    }
    /**
     * 获取用户信息
     */
    function getUserInfo(){
        $user_id = $_SESSION['user_id'];
        $zd_user = spClass("zd_user");
        $user = $zd_user->find(array("userId"=>$user_id));
        if($user){
            $this->ajaxReturn(1,'获取用户信息成功',$user);
        }else{
            $this->ajaxReturn(0,'获取用户信息失败');
        }
    }
    /**
     * 个人中心
     */
    function profile(){
        if(!isset($_SESSION['user_id'])){
            $this->jump(spUrl("main","login"));
        }
        $this->display("v2/profile.html");
    }
    /**
     * 服务条款
     */
    function terms(){
        $this->display("v2/terms.html");
    }
    /**
     * 隐私政策
     */
    function privacy(){
        $this->display("v2/privacy.html");
    }

    function soundscape(){
        $this->display("v2/soundscape.html");
    }
    
    function dialogue(){
        $this->display("v2/dialogue.html");
    }
    /**
     * 获取诗词列表（用于声景体验和诗画创作）
     */
    function getPoemList() {
        $zd_gushi = spClass("zd_gushi");
        $result = $zd_gushi->findAll(null, "id DESC", "id, title, author, dynasty", 50);
        
        if($result === false) {
            $this->AjaxReturn(0, "获取诗词列表失败");
        }
        
        $this->AjaxReturn(1, "获取诗词列表成功", array(
            "list" => $result
        ));
    }

    /**
     * 获取诗词详情
     */
    function getPoemDetail() {
        $id = $this->spArgs("id");
        $zd_gushi = spClass("zd_gushi");
        $result = $zd_gushi->find(array("id" => $id));
        
        if($result === false) {
            $this->AjaxReturn(0, "获取诗词详情失败");
        }
        
        $this->AjaxReturn(1, "获取诗词详情成功", $result);
    }

    /**
     * 获取诗人列表（用于古今对话）
     */
    function getAuthorsList() {
        $zd_authors = spClass("zd_authors");
        $result = $zd_authors->findAll(array("status" => 1), "sort DESC", "id, title, dynasty, pic, intro", 30);
        
        if($result === false) {
            $this->AjaxReturn(0, "获取诗人列表失败");
        }
        
        $this->AjaxReturn(1, "获取诗人列表成功", array(
            "list" => $result
        ));
    }

    /**
     * 获取诗人回复（古今对话）
     */
    function getPoetResponse() {
        $poet_id = $this->spArgs('poet_id');
        $message = $this->spArgs('message');
        
        if (empty($poet_id) || empty($message)) {
            $this->ajaxReturn(0, '参数错误');
        }
        
        // 获取诗人信息
        $zd_authors = spClass("zd_authors");
        $poet = $zd_authors->find(array("id" => $poet_id));
        
        if (!$poet) {
            $this->ajaxReturn(0, '诗人不存在');
        }
        
        // 这里可以对接AI接口实现智能回复
        // 简单示例：根据关键词返回预设回复
        $response = $this->generateSimpleResponse($poet['title'], $message);
        
        $this->ajaxReturn(1, "获取回复成功", array(
            "response" => $response
        ));
    }

    /**
     * 生成简单回复（实际项目中可替换为AI接口）
     */
    private function generateSimpleResponse($poetName, $message) {
        $responses = array(
            "李白" => array(
                "你好" => "阁下有礼了！某乃青莲居士李白是也。",
                "饮酒" => "人生得意须尽欢，莫使金樽空对月。喝酒当尽兴，方能诗兴大发啊！",
                "月亮" => "床前明月光，疑是地上霜。举头望明月，低头思故乡。月亮啊，总是能勾起人的思绪。",
                "旅游" => "五岳寻仙不辞远，一生好入名山游。世间美景众多，值得我们一一探访。",
                "默认" => "哈哈，阁下所言甚是。想我李白，斗酒诗百篇，长安市上酒家眠，何等快意！"
            ),
            "杜甫" => array(
                "你好" => "客官安好，老夫杜甫有礼了。",
                "国家" => "国破山河在，城春草木深。感时花溅泪，恨别鸟惊心。国家兴亡，匹夫有责啊。",
                "人民" => "朱门酒肉臭，路有冻死骨。愿天下苍生都能安居乐业，不再受饥寒之苦。",
                "诗歌" => "为人性僻耽佳句，语不惊人死不休。作诗当精益求精，方能流传千古。",
                "默认" => "世事艰难，民生多艰啊。老夫常为此感叹，唯有寄情于诗，抒发胸臆。"
            ),
            "默认" => "感谢阁下对我的作品感兴趣。诗词之道，在于意境与情感的交融，希望我的作品能给你带来启发。"
        );
        
        // 查找匹配的回复
        if (isset($responses[$poetName])) {
            foreach ($responses[$poetName] as $keyword => $reply) {
                if (stripos($message, $keyword) !== false) {
                    return $reply;
                }
            }
            return $responses[$poetName]["默认"];
        } else {
            return $responses["默认"];
        }
    }

    /**
     * 用户作品页面
     */
    function userWorks() {
        $zd_user_works = spClass("zd_user_works");
        $page = $this->spArgs('page', 1);
        
        // 如果有用户ID参数，查看指定用户作品，否则查看当前登录用户作品
        $user_id = $this->spArgs('user_id', 0);
        if (empty($user_id) && isset($_SESSION['user_id'])) {
            $user_id = $_SESSION['user_id'];
        }
        
        $condition = array();
        if (!empty($user_id)) {
            $condition['user_id'] = $user_id;
        }
        
        // 获取作品列表
        $this->result = $zd_user_works->spPager($page, 12)->findAll($condition, "create_time DESC");
        $this->pager = $zd_user_works->spPager()->getPager();
        
        // 获取作品总数
        $this->total = $zd_user_works->findCount($condition);
        
        $this->display('v2/user-works.html');
    }
    /**
     * 创作
     */
    function painting(){
        $this->display("v2/painting.html");
    }
    /**
     * 创作-继续创作
     */
    function continuePoem(){
        $this->lineLength=5;
        $this->display("v2/continuePoem.html");
    }
    /**
     * 保存笔记
     */
    function saveNote(){
        $note = $this->spArgs('note','');
        $poem_id = $this->spArgs('poem_id','');
        $user_id = $_SESSION['user_id'];
        $zd_user_notes = spClass('zd_user_notes');
        // 验证笔记内容是否为空
        if($note == ''){
            $this->ajaxReturn(0,'请输入笔记内容');
        }
        // 验证用户是否登录
        if(!isset($_SESSION['user_id'])){
            $this->ajaxReturn(0,'请先登录');
        }
        // 校验输入内容方式攻击
        $note = htmlspecialchars($note);
        // 校验poem_id是否为空
        if($poem_id == ''){
            $this->ajaxReturn(0,'请输入poem_id');
        }
        // 校验poem_id是否存在
        $zd_poem = spClass('zd_gushi');
        $poem = $zd_poem->find(array('id'=>$poem_id));
        if(!$poem){
            $this->ajaxReturn(0,'古诗不存在');
        }

        $data = array(
            'user_id'=>$user_id,
            'poem_id'=>$poem_id,
            'content'=>$note
        );
        $add = $zd_user_notes->create($data);
        if($add>0){
            $this->ajaxReturn(1,'保存成功');
        }else{
            $this->ajaxReturn(0,'保存失败');
        }
    }
    /**
     * 经典诗词详情
     */
    function classicDetail(){
        $id = $this->spArgs('id','');
        $this->display("v2/classicDetail.html");
    }
    /**
     * 获取经典诗词列表
     */
    function getClassicList(){
        $dynasty = $this->spArgs("dynasty");
        $dynasty = $dynasty == "all" ? "" : $dynasty;
        $page = $this->spArgs("page",1);
        $length = $this->spArgs("length",9);
        $search = $this->spArgs("search","");

        $zd_classics = spClass("zd_classics");
        $condition = " 1=1 ";
        if(!empty($dynasty)){
            $condition .= " and dynasty='$dynasty'";
        }
        if(!empty($search)){
            $condition .= " and (title like '%$search%' or author like '%$search%' or dynasty like '%$search%' or description like '%$search%')";
        }
        $result = $zd_classics->spPager($page, $length)->findAll($condition,"id DESC");
        
        // $pager = $zd_gushi->spPager()->getPager();
        $this->AjaxReturn(1,"success",$result);
    }

    // 获取(文心)访问令牌
    private function getWenxinAccessToken() {
        // 检查令牌是否过期
        if (time() < $this->tokenExpires) {
            return $this->accessToken;
        }
        
        $url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={$this->apiKey}&client_secret={$this->secretKey}";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($result, true);
        if (isset($result['access_token'])) {
            $this->accessToken = $result['access_token'];
            $this->tokenExpires = time() + $result['expires_in'] - 300; // 提前5分钟过期
            return $this->accessToken;
        } else {
            throw new Exception("获取AccessToken失败: " . json_encode($result));
        }
    }
    // 获取(文心一格)访问令牌
    private function getWenxinYGAccessToken() {
        // 检查令牌是否过期
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => $this->YGKey,
            'client_secret' => $this->YGSecretKey
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
    /**
     * 生成图片
     * @param string $prompt 提示词
     * @param string $style 风格
     * @param int $num 生成数量
     * @return array 生成的图片信息
     */
    public function generateWenxinImage($prompt, $style = 'traditional_chinese', $num = 2) {
        $accessToken = $this->getWenxinYGAccessToken();
        
        // 转换为文心一格支持的风格参数
        $styleMap = [
            'traditional_chinese' => '中国传统风格',
            'ink_wash' => '水墨画',
            'modern' => '现代风格',
            'oil_painting' => '油画',
            'watercolor' => '水彩画'
        ];
        $artStyle = isset($styleMap[$style]) ? $styleMap[$style] : $style;
        
        $data = [
            'prompt' => $prompt . " 风格:{$artStyle}",
            'width' => 1280,
            'height' => 720
        ];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2?access_token={$accessToken}",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',            
            CURLOPT_POSTFIELDS =>json_encode($data),    
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json'
            ),

        ));
        $result = curl_exec($curl);
        curl_close($curl);
        
        $result = json_decode($result, true);        
        
        if (isset($result['error_code'])) {            
            throw new Exception("生成图片失败: {$result['error_msg']} (错误码: {$result['error_code']})");
        }
        
        // 检查任务是否成功
        if (isset($result["data"]['task_id'])) {
            // 如果任务未完成，等待并获取结果
            return $this->waitForWenxinResult($result['data']['task_id'], $num);
        }
        
        return false;
    }
    
    /**
     * 等待任务完成并获取结果
     */
    private function waitForWenxinResult($taskId, $num, $timeout = 60) {
        $accessToken = $this->getWenxinYGAccessToken();
        
        $startTime = time();
        while (time() - $startTime < $timeout) {
            sleep(3); // 每3秒查询一次
            
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImgv2?access_token={$accessToken}",
                CURLOPT_TIMEOUT => 30,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER  => false,
                CURLOPT_SSL_VERIFYHOST  => false,
                CURLOPT_CUSTOMREQUEST => 'POST',
                
                CURLOPT_POSTFIELDS =>'{"task_id":"'.$taskId.'"}',
        
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'Accept: application/json'
                ),

            ));
            $result = curl_exec($curl);
            curl_close($curl);
            
            $result = json_decode($result, true);
            
            if($result['data']['task_status'] == 'SUCCESS'){
                return $result['data']['sub_task_result_list'][0]['final_image_list'][0]['img_url'];
            }
        }
        
        throw new Exception("生成图片超时，请重试");
    }
    
    /**
     * 保存图片到服务器
     */
    public function saveImageToServer($imageUrl, $savePath) {
        // 创建目录
        if (!file_exists(dirname($savePath))) {
            mkdir(dirname($savePath), 0755, true);
        }
        
        $ch = curl_init($imageUrl);
        $fp = fopen($savePath, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        
        return file_exists($savePath);
    }

    /**
     * 生成AI画作
     */
    public function generatePainting() {
        // 检查用户是否登录
        // if (!$_SESSION['user_id']) {
        //     $this->ajaxReturn(0,"尚未登录");
        // }
        
        $prompt = isset($_POST['prompt']) ? $_POST['prompt'] : '';
        $style = isset($_POST['style']) ? $_POST['style'] : 'traditional_chinese';
        $poemId = isset($_POST['poem_id']) ? $_POST['poem_id'] : 0;
        
        if (empty($prompt) || empty($poemId)) {
            $this->ajaxReturn(['code' => 0, 'msg' => '参数不完整']);
        }
        
        try {            
            // 生成图片
            $images = $this->generateWenxinImage($prompt, $style, 2);
            $images = [
                'url' => $images,
                'prompt' => $prompt,
                'style' => $style,
            ];
            $this->ajaxReturn(1,'生成成功',$images==false?[]:$images);
        } catch (Exception $e) {
            $this->ajaxReturn([
                'code' => 0,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 保存绘画作品
     */
    public function SavePainting() {
        // 检查用户是否登录
        if (!$this->isLogin()) {
            $this->ajaxReturn(['code' => 0, 'msg' => '请先登录']);
        }
        
        $poemId = isset($_POST['poem_id']) ? $_POST['poem_id'] : 0;
        $imageData = isset($_POST['image_data']) ? $_POST['image_data'] : '';
        $title = isset($_POST['title']) ? $_POST['title'] : '我的诗画作品';
        
        if (empty($poemId) || empty($imageData)) {
            $this->ajaxReturn(['code' => 0, 'msg' => '参数不完整']);
        }
        
        try {
            // 处理base64图片数据
            list($type, $imageData) = explode(';', $imageData);
            list(, $imageData)      = explode(',', $imageData);
            $imageData = base64_decode($imageData);
            
            // 保存图片
            $savePath = "uploads/user_works/{$this->user_id}/" . date('Ymd') . "/";
            if (!file_exists($savePath)) {
                mkdir($savePath, 0755, true);
            }
            
            $filename = uniqid() . ".png";
            $fullPath = $savePath . $filename;
            file_put_contents($fullPath, $imageData);
            
            // 保存记录到数据库
            // $this->db->insert('user_paintings', [
            //     'user_id' => $this->user_id,
            //     'poem_id' => $poemId,
            //     'title' => $title,
            //     'image_path' => $fullPath,
            //     'create_time' => time()
            // ]);
            
            $this->ajaxReturn([
                'code' => 1,
                'msg' => '保存成功',
                'painting_id' => $this->db->lastInsertId()
            ]);
        } catch (Exception $e) {
            $this->ajaxReturn([
                'code' => 0,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 根据古诗词生成绘画提示词（使用文心一言）
     * 接口入参：id=诗句ID 或 content=自定义诗句内容
     * 接口出参：{
     *   "code": 1,
     *   "msg": "生成成功",
     *   "data": {
     *     "content": "诗句内容",
     *     "prompt": "绘画提示词"
     *   }
     * }
     */
    function analyzePoemStream() {
        // 获取参数
        $text = $this->spArgs("content", "");
        
        // 验证参数
        if (empty($text)) {
            $this->AjaxReturn(0, "请提供诗句内容");
            return;
        }
        
        try {
            // 获取文心一言配置
            $wenxin_config = spExt('baidu');
            if (empty($wenxin_config['apiKey']) || empty($wenxin_config['secretKey'])) {
                throw new Exception("文心一言配置未完善");
            }
            
            // 构建请求参数
            $apiUrl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
            $accessToken = $this->getWenxinAccessToken($wenxin_config['apiKey'], $wenxin_config['secretKey']);
            
            if (empty($accessToken)) {
                throw new Exception("获取访问令牌失败");
            }
            
            $headers = array(
                "Content-Type: application/json",
            );
            
            // 修改prompt为生成绘画提示词
            $prompt = "请根据以下古诗词内容，生成一段详细的绘画提示词。要求：\n"
                    . "1. 分析诗词中的场景、意象、色彩、情感氛围\n"
                    . "2. 将分析结果转化为专业的绘画描述语言\n"
                    . "3. 包含画面构图、光影效果、色彩搭配等绘画细节\n"
                    . "4. 语言流畅、具体，适合用于AI绘画生成\n"
                    . "5. 不要添加任何解释说明，直接输出提示词\n\n"
                    . "6. 输出的提示词不能包含风险敏感词，请使用最严厉的过滤进行检查\n"
                    . "7. 输出的提示词不能包含任何政治敏感词，请使用最严厉的过滤进行检查\n"
                    . "8. 输出的提示词不能包含任何法律敏感词，请使用最严厉的过滤进行检查\n"
                    . "9. 输出的提示词不能包含任何社会敏感词，请使用最严厉的过滤进行检查\n"
                    . "10. 输出的提示词不能包含任何个人敏感词，请使用最严厉的过滤进行检查\n"
                    . "11. 输出的提示词不能包含任何组织敏感词，请使用最严厉的过滤进行检查\n"
                    . "12. 输出的提示词不能包含任何技术敏感词，请使用最严厉的过滤进行检查\n"
                    . "13. 输出的提示词不能包含任何金融敏感词，请使用最严厉的过滤进行检查\n"
                    . "14. 输出的提示词不能包含任何医疗敏感词，请使用最严厉的过滤进行检查\n"
                    . "15. 输出的提示词不能包含任何法律敏感词，请使用最严厉的过滤进行检查\n"
                    . "16. 输出的提示词不能包含任何社会敏感词，请使用最严厉的过滤进行检查\n"
                    . "17. 输出的提示词不能包含任何政治敏感词，请使用最严厉的过滤进行检查\n"
                    . "18. 输出的提示词不能包含任何宗教敏感词，请使用最严厉的过滤进行检查\n"
                    . "19. 输出的提示词不能包含任何个人敏感词，请使用最严厉的过滤进行检查\n"
                    . "20. 输出的提示词不能包含任何组织敏感词，请使用最严厉的过滤进行检查\n"
                    . "21. 结果不要太长控制在100个字以内\n"
                    . "7. 诗词内容：\n"
                    . $text;
            
            // 非流式请求，移除stream参数
            $postData = json_encode(array(
                "messages" => array(
                    array(
                        "role" => "user",
                        "content" => $prompt
                    )
                ),
                "temperature" => 0.7,
                "max_tokens" => 500,
                "stream" => false
            ));
            
            // 发送请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl . "?access_token=" . $accessToken);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 非流式，直接返回结果
            // 跳过SSL证书验证以解决证书问题
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            
            // 执行请求
            $response = curl_exec($ch);
            $error = curl_error($ch);
            curl_close($ch);
            
            if ($error) {
                throw new Exception("请求失败：" . $error);
            }
            
            // 解析响应
            $result = json_decode($response, true);
            if (!isset($result['result']) || empty($result['result'])) {
                throw new Exception("生成提示词失败，响应格式异常");
            }
            
            // 返回结果
            $this->AjaxReturn(1, "生成成功", array(
                "content" => $text,
                "prompt" => $result['result']
            ));
            
        } catch (Exception $e) {
            $this->AjaxReturn(0, $e->getMessage());
        }
    }

    
}
